// client
#include "client_command.h"

int main(int argc, char *argv[]) {
    // ./client ip port
    ARG_CHECK(argc, 3);

    int clientfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(clientfd, -1, "socket");

    // 绑定地址
    struct sockaddr_in serveraddr;
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(atoi(argv[2]));
    serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = connect(clientfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
    ERROR_CHECK(ret, -1, "bind");

    while (1) {
        // 读取输入
        char buf[100] = {0};
        int ret = read(STDIN_FILENO, buf, 100);
        if (ret == -1 && errno == EINTR) continue;
        else if (ret == -1) {
            perror("read");
            continue;
        }
        
        // 解析命令、执行命令
        handle_cmd(buf, clientfd);
    }

    // 关闭文件描述符
    close(clientfd);

    return 0;
}
